﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Wicture.EPC.Common
{
    public class VinHelper
    {
        private static readonly Dictionary<char, int> Dic_Character = new Dictionary<char, int>
        {
            { 'A', 1 },
            { 'B', 2 },
            { 'C', 3 },
            { 'D', 4 },
            { 'E', 5 },
            { 'F', 6 },
            { 'G', 7 },
            { 'H', 8 },
            { 'J', 1 },
            { 'K', 2 },
            { 'L', 3 },
            { 'M', 4 },
            { 'N', 5 },
            { 'P', 7 },
            { 'R', 9 },
            { 'S', 2 },
            { 'T', 3 },
            { 'U', 4 },
            { 'V', 5 },
            { 'W', 6 },
            { 'X', 7 },
            { 'Y', 8 },
            { 'Z', 9 },
            { '9', 9},
            { '8', 8},
            { '7', 7},
            { '6', 6},
            { '5', 5},
            { '4', 4},
            { '3', 3},
            { '2', 2},
            { '1', 1},
            { '0', 0},
            { '*', 0}
        };

        private static readonly Dictionary<int, int> Dic_Position = new Dictionary<int, int>
        {
            { 1, 8},
            { 2, 7},
            { 3, 6},
            { 4, 5},
            { 5, 4},
            { 6, 3},
            { 7, 2},
            { 8, 10},
            { 9, 0},
            { 10, 9},
            { 11, 8},
            { 12, 7},
            { 13, 6},
            { 14, 5},
            { 15, 4},
            { 16, 3},
            { 17, 2}
        };
        public static string GetCheckNo(string vin)
        {
            if (vin == null || vin.Length != 17)
            {
                return "";
            }
            var total = 0;
            for (int i = 0; i< vin.Length; i++)
            {
                var c = vin[i];
                if (!Dic_Character.ContainsKey(c))
                {
                    return "";
                }

                total += Dic_Character[c] * Dic_Position[i + 1];
            }

            var mod = total % 11;
            if (mod == 10) return "X";
            return mod.ToString();
        }

        public static bool CheckVinVaild(string vin)
        {
            return vin.Substring(8, 1) == GetCheckNo(vin);
        }
    }
}
